import { observable, action, computed, toJS } from 'mobx';
import { ListView } from 'weaver-mobile';

import Api from '../../apis/setting';

const initState = {
  params: { url: '', params: {} },
  loading: true,
  current: 0,
  datas: [],
  ops: [],
  checks: [],
  pageSize: 20,
  counts: 0,
  height: 0,
};

export default class TableListStore {
  @observable params = initState.params;
  @observable height = initState.height;
  @observable loading = initState.loading;
  @observable current = initState.current;
  @observable datas = initState.datas;
  @observable pageSize = initState.pageSize;
  @observable ops = initState.ops;
  @observable checks = initState.checks;
  @observable counts = initState.counts;
  @observable dataSource =  new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2,
  });

  constructor(params) {
    if (params) {
      this.params = params;
    }
  }

  @computed
  get hasMore() {
    return (this.pageSize * this.current) < this.counts;
  }

  @action
  updateDataSource = () => {
    this.dataSource = this.dataSource.cloneWithRows(toJS(this.datas));
  }

  @action
  refreshTableList = () => {
    this.getTableListDatas(null, true);
  }

  @action
  getTableListDatas = (api, refresh = false) => {
    if (!api) { api = this.params; }
    const page = refresh ? 1 : this.current + 1;
    this.loading = true;
    Api.callApi(api).then(res => {
      const { sessionkey } = res;
      if (sessionkey) {
        // datas
        Api.getDatas({ dataKey: sessionkey, current: page, pageSize: this.pageSize, sortParams: [] })
        .then(data => {
          const { datas, ops, pageSize } = data;
          this.datas = refresh ? [ ...datas ] : [ ...this.datas, ...datas ];
          this.ops = ops.filter(o => o.nodeName === 'operate');
          this.pageSize = Number(pageSize);
          if (datas && datas.length) { this.current = page; }
          // checks
          Api.getChecks({ dataKey: sessionkey, checkId: '', randomDatas: JSON.stringify(datas) })
          .then(checks => {
            this.checks = refresh ? [ ...checks.datas ] : [ ...this.checks, ...checks.datas ];
            this.updateDataSource();
            this.loading = false;
          });
        });
        // counts
        Api.getCounts({ dataKey: sessionkey })
        .then(counts => {
          const { count, status } = counts;
          if (Number(status)) {
            this.counts = count;
          }
        });
      }
    });
  }

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    return this;
  }

  @action
  clear = () => this.setState(initState)
}
